package com.carlwang.dao.imp;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

import com.carlwang.dao.AbstractTaskDao;
import com.carlwang.pojo.MyTask;
import com.carlwang.pojo.Profile;
import com.carlwang.pojo.TaskList;
import com.carlwang.util.HibernateUtil;

public class TaskDaoImp extends AbstractTaskDao {
	private HibernateUtil mHibernateUtil;

	@Override
	public void save(TaskList pTaskList, MyTask pMyTask, Profile pProfile) {
		Session session = getHibernateUtil().getSession();
		Transaction transaction = session.beginTransaction();
		Query query = session
				.createQuery("from TaskList taskList where taskList.id="
						+ pTaskList.getId());

		List list = query.list();
		TaskList taskList;
		List<MyTask> tasks;
		if (list.size() == 1) {
			taskList = (TaskList) list.get(0);
			tasks = taskList.getMyTaskList();
			tasks.add(pMyTask);
			session.update(tasks);
		}
		if (list.isEmpty()) {
			taskList = new TaskList();
			tasks = new ArrayList<MyTask>();
			tasks.add(pMyTask);
			taskList.setMyTaskList(tasks);
			session.save(taskList);
			List taskLists = new ArrayList<TaskList>();
			taskLists.add(taskList);
			pProfile.setTaskList(taskLists);
			session.save(pProfile);

		}
		getHibernateUtil().closeSession();
		transaction.commit();
	}

	@Override
	public Object load(Profile pProfile) {
		Session session = getHibernateUtil().getSession();
		Query query = session
				.createQuery("select profile.taskList from Profile as profile where profile.id=?");
		query.setLong(0, pProfile.getId());
		List<TaskList> taskList = query.list();
		getHibernateUtil().closeSession();
		return taskList;
	}

	public List getListType() {
		Session session = getHibernateUtil().getSession();
		Query query = session
				.createQuery("select listType.id from ListType listType");
		List list = query.list();
		getHibernateUtil().closeSession();
		return list;

	}

	public HibernateUtil getHibernateUtil() {
		return mHibernateUtil;
	}

	public void setHibernateUtil(HibernateUtil hibernateUtil) {
		mHibernateUtil = hibernateUtil;
	}

}
